import { useCallback, useState, useMemo } from 'react';
import MemberSelectCore from '@inbiz/basic/MemberSelect';
import { Select } from 'antd';
import _ from 'lodash';

const MemberSelect = (props: any) => {
  const {
    value = [],
    onChange,
    placeholder = '',
    config,
    disabled = false,
    allowClear = false,
  } = props;

  const {
    tabs = ['department', 'position', 'group', 'user'],
    multiple = true,
  } = config || {};

  const [visible, _visible] = useState(false);

  let realValue = _.isArray(value) ? value : [];
  let selectValue = useMemo(() => {
    if (_.isArray(realValue)) {
      return realValue?.map((v: any) => v.key);
    }
    return [];
  }, [realValue]);

  const options = useMemo(() => {
    if (_.isArray(realValue)) {
      return realValue?.map((v: any) => {
        return {
          label: v.name,
          value: v.key,
          'data-value': v,
        };
      });
    }
    return [];
  }, [realValue]);

  const handleChange = useCallback(
    (keys: any, rows: any) => {
      if (_.isEmpty(rows)) {
        onChange([]);
        return;
      }
      const newValue = [...rows].map((v) => {
        return {
          ...v['data-value'],
        };
      });
      onChange(newValue);
    },
    [onChange],
  );

  return (
    <>
      <MemberSelectCore
        visible={visible}
        config={{
          ...config,
          multiple: multiple,
          selected: realValue,
          tabs: tabs || [],
          onCancel: () => {
            _visible(false);
          },
          onOk: (keys, rows, map) => {
            onChange(rows);
            _visible(false);
          },
        }}
      />
      <Select
        placeholder={placeholder}
        onClick={() => {
          !disabled && _visible(true);
        }}
        dropdownStyle={{
          display: 'none',
        }}
        value={selectValue}
        onChange={handleChange}
        options={options}
        showSearch={false}
        showArrow
        mode={multiple && 'multiple'}
        allowClear={allowClear}
        onClear={() => {
          handleChange([], []);
        }}
        disabled={disabled}
      ></Select>
    </>
  );
};

export default MemberSelect;
